<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<style>
		.img{
			width:300px;
			height:300px;
		}
	</style>
</head>
<body>
	<iframe id="myIframe" name="myIframe" style="display: none"></iframe>
	<div id="container"></div>
	<form target="myIframe" id="uploadForm" method='POST' action="/upload/" enctype="multipart/form-data" >
		{% csrf_token %}
		<input type="text" id="imgtitle" name="imgtitle" />
		<input type="file" id="fileobj" name="fileobj" />
		<!--<input type="submit" value="iframe上传方式" />-->
	</form>

	<div>
		<input type="button" onclick="uploadFile1();" value="XMLHttpRequest按钮（原生ajax)"/>
	</div>
	<div>
		<input type="button" onclick="uploadFile2();" value="jQueryAjax按钮" />
	</div>
	<div>
		<input type="button" onclick="uploadFile3();" value="伪Ajax按钮" />
	</div>


	<script src="/static/jquery-2.1.1.min.js"></script>

	<script>
		//<!--Jquery Ajax上传方法-->
		function uploadFile1(){
			var form = new FormData()
			form.append('imgtitle',document.getElementById('imgtitle').value);
			var fileObj = document.getElementById("fileobj").files[0];
			form.append("fileobj",fileObj);
			form.append('csrfmiddlewaretoken','{{ csrf_token }}');
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					var data = xhr.responseText;
					console.log(data);
				}
			};
			xhr.open("post",'/upload/',true);
			xhr.send(form);
		}

	  //<!-- Jquery Ajax上传方法 -->
		function uploadFile2(){
			var form = new FormData();
			form.append('csrfmiddlewaretoken','{{ csrf_token }}');
			form.append('fileobj',$('#fileobj')[0].files[0]);
			form.append('imgtitle',document.getElementById('imgtitle').value);
			$.ajax({
				type:'POST',
				url:'/upload/',
				data:form,
				processData:false,
				contentType:false,
				success:function(result){
					console.log(result);
				}
			})
		}

		//<!-- ifarm伪ajax上传方法 -->
		function uploadFile3(){
			$('#container').find('img').remove();
			//document.getElementById('uploadForm').target = 'myIframe';  //target接的是name属性,在form表单可以直接设置

			document.getElementById('myIframe').onload = callbak;
			document.getElementById('uploadForm').submit();
		}
		function callbak(){
			var text = $('#myIframe').contents().find('body').text();  //找到这个ID的内容,这个是后端返回的json数据
			var json_data = JSON.parse(text);
			if(json_data.status){
				var tag = document.createElement('img');
				tag.src='/'+ json_data.data;
				tag.className = 'img';
				$('#container').append(tag);
			}else{
				alert(json_data.errMessage)
			}

		}
	</script>

</body>
</html>